<?php
namespace App\Admin\Controllers;

use App\Models\Common\File;
use App\Models\Common\Media;
use Dcat\Admin\Admin;
use Dcat\Admin\Support\Helper;
use Dcat\Admin\Traits\HasUploadedFile;

class UploadImageController
{
    use HasUploadedFile;

    public function handle()
    {
        $disk = $this->disk();

        // 判断是否是删除文件请求
        if ($this->isDeleteRequest()) {
            // 删除文件并响应
            return $this->responseDeleted();
        }

        // 获取上传的文件
        $file = $this->file();

        $path = $file->getRealPath();
        $md5 = md5_file($path);
        $ext = $file->getClientOriginalExtension();

        $path1 = substr($md5, 0, 3);
        $path2 = substr($md5, 3, 3);
        $filename = $md5.'.'.$ext;
        $foldpath = 'uploads/images/'.$path1.'/'.$path2.'/';
        $path = $foldpath . $filename;

        $admin_user_id = Admin::user()->id;

        $isexist = $disk->exists($path);
        if(!$isexist) {
            $result = $disk->putFileAs($foldpath, $file, $filename);
            if(!$result) {
                return $this->responseErrorMessage('文件上传失败');
            }
        }
        $m_file = File::firstOrCreate(
            ['md5'=>$md5],
            [
                'url'=>$path,
                'ext'=>$ext,
                'foldpath'=>$foldpath,
                'filesize'=>$file->getSize()
            ]
        );

        $m_media = Media::firstOrCreate(
            [
                'filename'=>$file->getClientOriginalName(),
                'url'=>$disk->url($path),
                'file_id'=>$m_file->id,
                'admin_user_id'=>$admin_user_id,
            ]
        );

        return Admin::json([
            'id'   => $m_media->id,
            'name' => $m_media->filename,
            'path' => $foldpath,
            'url'  => $disk->url($path),
        ]);
    }
}
